package com.youfang.sixthmedia.common;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.OverlayItem;
import com.baidu.mapapi.Projection;
import com.youfang.sixthmedia.R;
import com.youfang.sixthmedia.message.model.Building;
import com.youfang.sixthmedia.ui.detail.TabDetailBuildingActivity;

public class BaiduMapActivity extends MapActivity {

	protected MapView mapview;
	protected Drawable mapMarker;
	protected View mapPopView;

	protected BaiduMapActivity that = this;

	protected class BuildingOverlayItem extends OverlayItem {
		public Building building;

		public BuildingOverlayItem(GeoPoint point, String title,
				String snippet, Building building) {
			super(point, title, snippet);
			this.setMarker(mapMarker);
			this.building = building;

		}

	}

	protected class BuildingOverlay extends ItemizedOverlay<OverlayItem> {

		private List<BuildingOverlayItem> mGeoList = new ArrayList<BuildingOverlayItem>();

		public BuildingOverlay(Drawable marker, Context context) {
			super(boundCenterBottom(marker));
		}

		public BuildingOverlay(Context context, Building b) {

			super(mapMarker);

			GeoPoint point = b.getGeoPoint();

			BuildingOverlayItem item = new BuildingOverlayItem(point,
					b.buildingname, b.pricedesc, b);
			mGeoList.add(item);

			populate();
		}

		public BuildingOverlay(Context context, List<Building> buildings) {
			super(mapMarker);
			for (Building b : buildings) {
				// 用给定的经纬度构造GeoPoint，单位是微度 (度 * 1E6)
				GeoPoint point = b.getGeoPoint();

				BuildingOverlayItem item = new BuildingOverlayItem(point,
						b.buildingname, /* b.pricedesc */
						"0".equals(b.price) ? "价格待定" : b.price + "元/㎡", b);
				mGeoList.add(item);
			}
			populate();
		}

		@Override
		public void draw(Canvas canvas, MapView mapview, boolean shadow) {

			// Projection接口用于屏幕像素坐标和经纬度坐标之间的变换
			Projection projection = mapview.getProjection();
			for (int index = size() - 1; index >= 0; index--) {
				BuildingOverlayItem overlayItem = (BuildingOverlayItem) getItem(index);
				// 得到给定索引的item
				//
				// GeoPoint geopoint = overlayItem.getPoint();
				// Point point = projection.toPixels(geopoint, null);
				//

				Drawable drawable = overlayItem
						.getMarker(OverlayItem.ITEM_STATE_NORMAL_MASK);

				ItemizedOverlay.boundCenterBottom(drawable);
				Rect bound = drawable.getBounds();
				drawable.setBounds(bound.left,
						bound.top + drawable.getIntrinsicHeight(), bound.right,
						bound.bottom + drawable.getIntrinsicHeight());

			}

			super.draw(canvas, mapview, shadow);

			// 调整一个drawable边界，使得（0，0）是这个drawable底部最后一行中心的一个像素
			// boundCenterBottom(marker);

		}

		@Override
		protected OverlayItem createItem(int i) {
			return mGeoList.get(i);
		}

		@Override
		public int size() {
			return mGeoList.size();
		}

		@Override
		// 处理当点击事件
		protected boolean onTap(int i) {
			setFocus(mGeoList.get(i));

			// 更新气泡位置,并使之显示
			GeoPoint pt = mGeoList.get(i).getPoint();

			that.mapview.updateViewLayout(that.mapPopView,
					new MapView.LayoutParams(LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT, pt,
							MapView.LayoutParams.BOTTOM_CENTER));

			// 位置的显示信息
			TextView name = (TextView) that.mapPopView
					.findViewById(R.id.location_name);

			String showdesc = mGeoList.get(i).getTitle() + "<br>"
					+ mGeoList.get(i).getSnippet();
			name.setText(Html.fromHtml(showdesc.toString()));

			that.mapPopView.setVisibility(View.VISIBLE);

			// goto building detail...
			final BuildingOverlayItem item = (BuildingOverlayItem) this
					.getItem(i);
			that.mapPopView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {

					Intent intent = new Intent();
					intent.setClass(that, TabDetailBuildingActivity.class);
					intent.putExtra("id", item.building.id);
					that.startActivity(intent);

				}
			});

			return true;
		}

		@Override
		public boolean onTap(GeoPoint arg0, MapView arg1) {
			// 消去弹出的气泡
			that.mapPopView.setVisibility(View.GONE);
			return super.onTap(arg0, arg1);
		}
	}

	// 将所有点都显示出来
	protected void fitPoints(List<Building> points) {
		// set min and max for two points
		int nwLat = -90 * 1000000;
		int nwLng = 180 * 1000000;
		int seLat = 90 * 1000000;
		int seLng = -180 * 1000000;
		// find bounding lats and lngs
		for (Building point : points) {
			nwLat = Math.max(nwLat, point.getLatitudeE6());
			nwLng = Math.min(nwLng, point.getLongitudeE6());
			seLat = Math.min(seLat, point.getLatitudeE6());
			seLng = Math.max(seLng, point.getLongitudeE6());
		}
		GeoPoint center = new GeoPoint((nwLat + seLat) / 2, (nwLng + seLng) / 2);
		// add padding in each direction
		int spanLatDelta = (int) (Math.abs(nwLat - seLat) * 1.2);
		int spanLngDelta = (int) (Math.abs(seLng - nwLng) * 1.2);

		// fit map to points
		mapview.getController().zoomToSpan(spanLatDelta, spanLngDelta);
		mapview.getController().animateTo(center);

	}

	// 将某个点移动到地图中间
	protected void moveToCenter(Building building) {
		mapview.getController().animateTo(building.getGeoPoint());

	}

	// NOTE:子类需要在setContentView之后，再调用super.onCreate方法，才能顺利完成map activity的初始化
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		// ////////////////初始化地图相关的内容////////////////
		mapview = (MapView) this.findViewById(R.id.mapview);
		if (mapview != null) {
			BaiduMapApplication app = (BaiduMapApplication) this
					.getApplication();
			app.ensureMananger();
			if (!app.isMapServiceReady()) {
				return;
			}
			app.startMapService();
			BMapManager manager = app.getMapManager();
			super.initMapActivity(manager);

			mapview.setBuiltInZoomControls(true);

			// mapview.getController().setZoom(mapview.getZoomLevel()-1);

			// 设置在缩放动画过程中也显示overlay,默认为不绘制
			// mapview.setDrawOverlayWhenZooming(true);

			// 得到需要标在地图上的资源
			// 地图标记
			mapMarker = getResources().getDrawable(R.drawable.map_mark);
			mapMarker.setBounds(0, 0, mapMarker.getIntrinsicWidth(),
					mapMarker.getIntrinsicHeight()); // 为maker定义位置和边界

			// 信息的弹出气泡
			mapPopView = super.getLayoutInflater().inflate(
					R.layout.map_popview, null);
			mapview.addView(mapPopView, new MapView.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, null,
					MapView.LayoutParams.TOP_LEFT));
			mapPopView.setVisibility(View.GONE);
		}

	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	// @Override
	// protected void onStop() {
	// super.onStop();
	// BaiduMapApplication app = (BaiduMapApplication) this.getApplication();
	// app.stopMapService();
	// }
	@Override
	protected void onPause() {

		BaiduMapApplication app = (BaiduMapApplication) this.getApplication();
		app.stopMapService();

		super.onPause();
	}

	@Override
	protected void onResume() {
		BaiduMapApplication app = (BaiduMapApplication) this.getApplication();
		app.startMapService();
		super.onResume();
	}

}
